package org.igeek.atomqq.task;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.igeek.atomqq.activity.BaseActivity;
import org.igeek.atomqq.domain.Friend;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.HttpConnection.Request_TYPE;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.util.URLManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


/**
 * 获取在线好友列表
 * 正常返回类型: text/plain
 * 
 * GET text/plain	http://d.web2.qq.com/channel/get_online_buddies2?clientid=77722341&psessionid=令牌&t=1328451724505时间
 * @author hangxin1940@gmail.com
 * @version 创建时间：2012-1-29 下午1:32:26
 * 
 */
public class FriendOnlineTask extends SingleAsyncTask<Void,Void,Void>{
	public static final int ERROR=0x5026;
	
	private TaskResultListener listener;
	private FriendOnlineListResponse response;
	private int flag;
	
	private Handler handler=new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ERROR:
				activity.showDialog(ERROR, msg.getData());
				
				break;
			default:
				activity.showDialog(BaseActivity.DIALOG_ERROR, msg.getData());
				break;
			}
		}
	};
	
	private BaseActivity activity;
	
	public FriendOnlineTask(BaseActivity activity){
		this.activity=activity;
	}
	
	public void setOnTaskResult(TaskResultListener listener,int flag){
		this.listener=listener;
		this.flag=flag;
	}
	

	@Override
	protected Void doInBackground(Void... params) {
		
		
		try {
			
			String time=new Date().getTime()+"";
			String psessionid=HttpConnection.getCookieManager().getCookieValue("psessionid");
			String clientid=HttpConnection.getCookieManager().getCookieValue("clientid");
			StringBuffer surl=new StringBuffer(URLManager.ONLINE_FRIENDS);
			surl.append("?clientid=");
			surl.append(clientid);
			surl.append("&psessionid=");
			surl.append(psessionid);
			surl.append("&t=");
			surl.append(time);
			
			
			
			URL url = new URL(surl.toString());
			
			HttpConnection conn=new HttpConnection(url, Request_TYPE.GET);
			conn.setReferer(URLManager.REFER_d_web2_qq_com_proxy);
			conn.connect();
			Response cesponses=conn.getResponse();
			conn.disconnect();
			
			JSONObject r=cesponses.getJsonObj();
			JSONArray result=r.getJSONArray("result");
			
			List<Friend> friends=createFriend(result);
			
			response=new FriendOnlineListResponse();
			response.setOnlineFriends(friends);
			
			
			
		}catch (Exception e) {
			e.printStackTrace();
			showErrorDialog("网络异常",ERROR);
		}
		
		
		return null;
	}
	

	
	/**
	 * 组装好友列表
	 * @param frs
	 * @return
	 * @throws JSONException 
	 */
	private List<Friend> createFriend(JSONArray frs) throws JSONException{
		List<Friend> friends=Collections.synchronizedList(new ArrayList<Friend>());
		
		
		if(frs.length() > 0	&& frs.getJSONObject(0).getLong("uin") == -2)
			throw new JSONException("好友列表获取错误");
		
		//好友信息
		for (int i = 0; i < frs.length(); i++) {
			JSONObject jfriend = frs.getJSONObject(i);	
			long uin=jfriend.getLong("uin");
			String status=jfriend.getString("status");
			int client_type=jfriend.getInt("client_type");
			
			
			Friend friend=new Friend(uin);
			friend.setStatus(status);
			friend.setClient_type(client_type);
			friends.add(friend);
			
		}
		
		
		
		return friends;
	}
	
	private void showErrorDialog(String message,int flag){
		Bundle bundle=new Bundle();
		bundle.putString(BaseActivity.FLAG_ERROR, message);
		Message msg=new Message();
		msg.setData(bundle);
		msg.what=flag;
		handler.sendMessage(msg );
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if(null!=response)
			listener.onTaskResult(response,flag);
	}	

	
	public class FriendOnlineListResponse extends Response{
		private List<Friend> friends;

		public void setOnlineFriends(List<Friend> friends) {
			this.friends = friends;
		}

		public List<Friend> getOnlineFriends() {
			return friends;
		}

		
	}
}
